from bddjango import get_field_names_by_model
import os


class FileFieldModelMixin:
    """
    将文件字段`field_name`的默认文件名按照`bian_hao_name`进行转换, 转换的文件格式为`file_format`

    --- eg:
        field_name = 'yin_pin_wen_jian_ming'
        bian_hao_name = 'yin_pin_bian_hao'
        file_format = 'jpg'
        self.file_filed(field_name, bian_hao_name, file_format)
    """
    def file_field(self, field_name, bian_hao_name='pk', file_format='jpg'):
        if file_format.startswith('.'):
            file_format = file_format[1:]

        assert hasattr(self, bian_hao_name), f'请确认bian_hao_name[{bian_hao_name}]是否正确!'
        if getattr(self, bian_hao_name) is None and bian_hao_name not in ['id', 'pk']:
            setattr(self, bian_hao_name, self.pk)

        index = get_field_names_by_model(self, 'name').index(field_name)
        assert index != -1, f'index不存在?请确认field_name[{field_name}]是否正确!'
        f = self._meta.fields[index]
        upload_to = f.upload_to

        attr = getattr(self, field_name)
        bulk_import_flag = not attr.readable()  # 判断是否存在file, 不存在则为批量导入
        if bulk_import_flag:
            attr.name = os.path.join(upload_to, f"{getattr(self, bian_hao_name)}.{file_format}")
        setattr(self, field_name, attr)